var editRowsNumber, _datasDatagrid, selectForm,listBugType,listBugType1,dialogBugReplys;
var bugReplysId,name,btname,status,bugReplys,note,flagBug;
var createDate1,createDate2,checkName,checkBtid,checkStatus;

function addBug() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		$('#name').val('').removeAttr('readonly');
		$('#btname').combobox('setValue', 1);
		$('#status').combobox('setValue', 1);
		note.readonly(false);
		bugReplys.readonly();
		note.html('');
		bugReplys.html('');
		flagBug = 1;
		dialogBugReplys.dialog({iconCls:'icon-bug_add'}).dialog('setTitle', '提交BUG').dialog('open');
	}
}

function addRow() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		_datasDatagrid.datagrid('insertRow', {index: 0, row: {}});
		_datasDatagrid.datagrid('beginEdit', 0);
		editRowsNumber = 0;
	}
};

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/bug/delete", {ids:ids.join(",")}, function(data) {
					if (data && data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
};

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var index = _datasDatagrid.datagrid('getRowIndex', rows[0]);
			_datasDatagrid.datagrid('beginEdit', index);
			editRowsNumber = index;
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
};

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
};

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
};

function search_datas() {
	_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
}

function reset_datas() {
	createDate1.datebox('setValue', '');
	createDate2.datebox('setValue', '');
	checkBtid.combobox('setValue', '');
	checkStatus.combobox('setValue', '');
	checkName.val('');
	_datasDatagrid.datagrid('load',{});
}

$(function() {
	editRowsNumber = -1;
	_datasDatagrid = $('#_datasDatagrid');
	selectForm = $('#selectForm');
	listBugType = $('#listBugType').val();
	
	createDate1 = $('#createDate1').datebox({editable:false}).datebox('activeTextArrow');
	createDate2 = $('#createDate2').datebox({editable:false}).datebox('activeTextArrow');
	checkName = $('#checkName').validatebox({validType:['unnormal','maxLength[200]']});
	checkBtid = $('#checkBtid').combobox({editable:false,valueField:'id',textField:'name'}).combobox('activeTextArrow');
	checkStatus = $('#checkStatus').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=紧急程度"
	}).combobox('activeTextArrow');
	
	bugReplysId = $('#bugReplysId').val();
	name = $('#name').validatebox({required:true,validType:['maxLength[200]']});
	btname = $('#btname').combobox({editable:false,required:true,valueField:'id',textField:'name'}).combobox('activeTextArrow').combobox('setValue', 1);
	status = $('#status').combobox({valueField:'code',textField:'name',editable:false,
		url:sy.bp() + "/admin/dictionary/listDictionary?name=紧急程度"
	}).combobox('activeTextArrow');
	if (listBugType) {
		btname.combobox('loadData', $.evalJSON(listBugType));
		checkBtid.combobox('loadData', $.evalJSON(listBugType));
	} else {
		$.post(sy.bp() + "/admin/bug/findBugType", function(data) {
			if (data && data.result==1) {
				btname.combobox('loadData', data.obj);
				checkBtid.combobox('loadData', data.obj);
				listBugType1 = data.obj;
			}
		}, "json");
	}
	dialogBugReplys = $('#dialogBugReplys').show().dialog({
		title : '解决BUG',
		iconCls : 'icon-bug_delete',
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
		buttons : [{
			text : '提交',
			handler : function(){ 
				var datas = {
					name : $('#name').val(),
					btid : $('#btname').combobox('getValue'),
					status : $('#status').combobox('getValue'),
					note : note.html(),
					bugReplys : bugReplys.html()
				};
				var url = sy.bp()+"/admin/bug/";
				if (flagBug) {
					url += "add";
				} else {
					datas.id = bugReplysId;
					url += "update";
				}
				$.post(url,datas,function(data){
					if(data && data.result ==1) {
						dialogBugReplys.dialog('close');
						_datasDatagrid.datagrid('reload');
						$.messager.show({title:'系统提示', msg:'提交成功!', timeout:2000, showType:'slide'});
					} else {
						$.messager.alert('系统提示', data.msg);
					};
				},"json");
			}
		}]
	});
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/bug/list',
		fit : true,
		autoRowHeight : true,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : true,
		border : false,
		idField : 'id',
		sortName : 'createTime',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
		          {text:'增加',iconCls: 'icon-add',handler: addRow},'-',
		          {text:'批量删除',iconCls: 'icon-remove',handler: deleteRow},'-',
		          {text:'编辑',iconCls: 'icon-edit',handler: updateRow},'-',
		          {text:'保存',iconCls: 'icon-save',handler: saveRow},'-',
		          {text:'撤销',iconCls: 'icon-redo',handler: rejectRow},'-',
		          {text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}},'-',
		          {text:'提交BUG',iconCls: 'icon-bug_add',handler: addBug}
		         ],
		frozenColumns: [[
		                 {field:'id',title:'编号',align:'center',width:100,sortable:true,checkbox:true},
		                 {field:'name',title:'名称',align:'left',width:100,sortable:true,
		                	 editor:{type:'validatebox',options:{required:true,validType:['maxLength[200]']}}}
					   ]],
		columns:[[
		          {field:'btid',title:'类型',align:'center',width:100,sortable:true,
		        	  formatter:function(value, row) {if (value) {return row.btname;} return ''; },
		        	  editor:{type:'combobox',options:{required:true,editable:false,valueField:'id',textField:'name',
		  				 onShowPanel:function() {
		  					if (listBugType){
		  						$(this).combobox('loadData', $.evalJSON(listBugType));
		  					} else {
		  						$(this).combobox('loadData', listBugType1);
		  					}
		  				}
		        	  }}
		          },
		          {field:'btname',title:'类型',align:'center',width:100,hidden:true},
		          {field:'note',title:'描述',align:'left',width:300,
		        	  editor:{type:'validatebox',options:{required:true,validType:['maxLength[200]']}}},
		          //{field:'bugReplys',title:'回复',align:'left',width:300},
		          {field:'status',title:'紧急程度',align:'left',width:100,sortable:true,
		        		  formatter:function(value, row) {
				        	  if (value == 1) {
				        		  return "☆";
				        	  } else if (value == 2) {
				        		  return "☆☆";
				        	  } else if (value == 3) {
				        		  return "☆☆☆";
				        	  } else if (value == 4) {
				        		  return "☆☆☆☆";
				        	  } else if (value == 5) {
				        		  return "☆☆☆☆☆";
				        	  } else {
				        		  return "已解决";
				        	  }
		        		  },
		        		  editor:{type:'combobox',
		        			  options:{
		        				  valueField:'code',
		        				  textField:'name',
		        				  editable:false,
		        				  url:sy.bp() + "/admin/dictionary/listDictionary?name=紧急程度"
		        			  }
		        		  }
		          },
		          {field:'createName',title:'创建人', align:'left',width:100,sortable:true},
		          {field:'createTime',title:'创建时间',align:'left',width:100,sortable:true},
		          {field:'modifyName',title:'修改人', align:'left',width:100,sortable:true},
		          {field:'modifyTime',title:'修改时间',align:'left',width:100,sortable:true}
				]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				$('#name').val(rowData.name).attr("readonly","readonly");
				$('#btname').combobox('setValue', rowData.btid);
				$('#status').combobox('setValue', rowData.status);
				note.readonly();
				bugReplys.readonly(false);
				note.html(rowData.note);
				bugReplys.html(rowData.bugReplys);
				flagBug = 0;
				bugReplysId = rowData.id;
				var historyText = "";
				$.each(rowData.listBugReplys, function(i, item) {
					if (item.reply) {
						historyText += "<span style='color:red;'>" + item.createTime + "</span>" +item.createName + "回复:" + item.reply + "</br>";
					}
				});
				$('#history').html(historyText);
				dialogBugReplys.dialog({iconCls:'icon-bug_delete'}).dialog('setTitle', '解决BUG').dialog('open');
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		},
		onAfterEdit : function(rowIndex, rowData, changes) {
			var inserted = _datasDatagrid.datagrid('getChanges', 'inserted');
			var updated = _datasDatagrid.datagrid('getChanges', 'updated');
			if (inserted.length < 1 && updated.length < 1) {
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
				return;
			}
			var url='';
			if (inserted.length > 0) {
				url=sy.bp()+'/admin/bug/add';
			}
			if (updated.length > 0) {
				url=sy.bp()+'/admin/bug/update';
			}
			$.post(url, rowData, function(data) {
				if (data && data.result==1) {
					_datasDatagrid.datagrid('acceptChanges');
					$.messager.show({msg:data.msg,title:'系统提示'});
					_datasDatagrid.datagrid('reload');
				} else {
					_datasDatagrid.datagrid('rejectChanges');
					$.messager.alert('错误', data.msg, 'warning');
				}
				editRowsNumber = -1;
				_datasDatagrid.datagrid('unselectAll');
			}, "json");
		}
	});
});

KindEditor.ready(function(K) {
	note = K.create('textarea[name="note"]', {
		width : '700px',
		minWidth : '700px',
		resizeType : 0,
		readonlyMode : true,
		allowPreviewEmoticons : false,
		allowImageUpload : false,
		items : [
			'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
			'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
			'insertunorderedlist', '|', 'emoticons', 'image', 'link'],
		autoHeightMode : true,
		afterCreate : function() {
			this.loadPlugin('autoheight');
		}
	});
	bugReplys = K.create('textarea[name="bugReplys"]', {
		width : '700px',
		minWidth : '700px',
		resizeType : 0,
		readonlyMode : true,
		allowPreviewEmoticons : false,
		allowImageUpload : false,
		items : [
			'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
			'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
			'insertunorderedlist', '|', 'emoticons', 'image', 'link'],
		autoHeightMode : true,
		afterCreate : function() {
			this.loadPlugin('autoheight');
		}
	});
});
